package com.dylan.datacollection;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dylan.datacollection.db.SharedPreferencesUtils;
import com.dylan.datacollection.entity.UserEntity;
import com.dylan.datacollection.net.HttpConfig;
import com.dylan.datacollection.net.HttpHelper;
import com.dylan.datacollection.net.ResponseCallback;
import com.dylan.datacollection.utils.ToastUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;

public class ScoreActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener,View.OnClickListener{
    Context context;
    ImageView checkImg;
    TextView orderTextView;
    TextView totalTextView;
    TextView currentScoreTextView;
    SeekBar seekBar;
    int progress = 100;
    String totalScore;
    String score_ave;
    String total_num;
    String checkId;
    Uri photoUri;
    TextView addressTextView;
    ProgressDialog progressDialog;
    private String path = Environment.getExternalStorageDirectory() +
            File.separator + Environment.DIRECTORY_DCIM + File.separator;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        context = this;
        checkId = getIntent().getStringExtra("id");
        checkImg = (ImageView) findViewById(R.id.score_imageView);
        findViewById(R.id.take_photo_button).setOnClickListener(this);
        findViewById(R.id.submit_button).setOnClickListener(this);
        currentScoreTextView = (TextView) findViewById(R.id.end_score);
        seekBar = (SeekBar) findViewById(R.id.seekBar2);
        seekBar.setOnSeekBarChangeListener(this);
        orderTextView = (TextView) findViewById(R.id.score_listorder_textView);
        totalTextView = (TextView) findViewById(R.id.score_totalscore_textView);
        addressTextView = (TextView) findViewById(R.id.score_address);
        getCheckInfo(checkId);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    public ProgressDialog createProgressBar(){
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("数据上传中...");
        return progressDialog;
    }
    public void getCheckInfo(String id){
        HttpHelper.getInstance().checkInfo(id,new ResponseCallback(){
            @Override
            public void onResponse(Object response, int id) {
                super.onResponse(response, id);
                try {
                    Log.i("score","response check info:"+response.toString());
                    JSONObject jsonObject = new JSONObject(response.toString());
                    if (jsonObject.optInt("code") == HttpConfig.SUCCESS){
                        Glide.with(context).load(jsonObject.getJSONObject("data").getString("check_img")).placeholder(R.mipmap.bg_default).thumbnail(0.1f).error(R.mipmap.bg_default).skipMemoryCache(false).into(checkImg);
                        addressTextView.setText(jsonObject.getJSONObject("data").getString("address"));
                        orderTextView.setText(jsonObject.getJSONObject("data").getString("pm")+"\n当前排名");
                        totalTextView.setText(jsonObject.getJSONObject("data").getString("pjf")+"\n当前平均分");
                        totalScore = jsonObject.getJSONObject("data").getString("total_score");
                        total_num = jsonObject.getJSONObject("data").getString("total_num");
                        score_ave = jsonObject.getJSONObject("data").getString("pjf");
                    }else{
                        ToastUtils.showShortMsg(context,jsonObject.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                ToastUtils.showLongMsg(context,e.getMessage());
                Log.i("score","response check info error:"+e.getMessage());
            }
        });
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            currentScoreTextView.setText(progress+"分");
        this.progress = progress;
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.take_photo_button:
                String state = Environment.getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    String fileName = getPhotoFileName() + ".jpg";
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    photoUri = Uri.fromFile(new File(path + fileName));
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                    startActivityForResult(intent, 6813);
                }
                break;
            case R.id.submit_button:
                if (photoUri!=null){
                    try {
                        File file = new File(new URI(photoUri.toString()));
                        Gson gson = new Gson();
                        UserEntity userEntity = gson.fromJson(SharedPreferencesUtils.readString(context,"user",""),UserEntity.class);
                        progressDialog = createProgressBar();
                        progressDialog.show();
                        HttpHelper.getInstance().submitInfo(total_num,score_ave,totalScore,checkId,userEntity.getId(),String.valueOf(progress),file,new ResponseCallback(){
                            @Override
                            public void onResponse(Object response, int id) {
                                super.onResponse(response, id);
                                try {
//                                    Log.i("score","response success:"+response.toString());
                                    JSONObject jsonObject = new JSONObject(response.toString());
                                    progressDialog.cancel();
                                    ToastUtils.showShortMsg(context,jsonObject.optString("msg"));
                                    if (jsonObject.optInt("code") == HttpConfig.SUCCESS){
                                        getCheckInfo(checkId);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onError(Call call, Exception e, int id) {
                                super.onError(call, e, id);
                                progressDialog.cancel();
                                ToastUtils.showLongMsg(context,"id:"+id+";error:"+e.getMessage());
                                Log.i("score","response error:"+e.getMessage());
                            }
                        });
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }else{
                    ToastUtils.showLongMsg(context,"您还没有拍照！");
                }
                break;
        }
    }
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return "IMG_" + dateFormat.format(date);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == 6813) {

            Uri uri = null;
            if (data != null && data.getData() != null) {
                uri = data.getData();
            }
            if (uri == null) {
                if (photoUri != null) {
                    uri = photoUri;
                }
            }
            photoUri = uri;
            Log.i("SORE","response:"+uri);
            Glide.with(context).load(uri).placeholder(R.mipmap.bg_default).thumbnail(0.1f).error(R.mipmap.bg_default).skipMemoryCache(false).into(checkImg);

        }
    }
}
